package com.suning.sawp.service.custProtrait;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.BASE64Encoder;

/**
 * 编写发送者的功能：首先通过私钥加密待输出数据Data，并输出Data和签名后的Data；
 * 
 * @author 15050963
 *
 */
@SuppressWarnings("restriction")
public class SignatureData {

    private static final char[] bcdLookup = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
            'f' };

    private static final Logger LOGGER = LoggerFactory.getLogger(SignatureData.class);

    /**
     * 替换会员加密字符串
     * 
     * @param url
     * @param custNo
     * @return
     */
    public static String wrapMemberProtraitUrl(String url, String custNo, String priKey) {
        // 会员编码（加密后）
        String custNumEncrypt = "";
        try {
            custNumEncrypt = encryptBASE64(custNo);
        } catch (Exception e) {
            LOGGER.error("SignatureData.wrapMemberProtraitUrl", e);
        }
        // 生成价签信息--根据会员号+秘钥
        String signKey = getSignKey(custNo, priKey);

        return url.replace("${custNum}", custNumEncrypt).replace("${signKey}", signKey);
    }

    public static String getSignKey(String custNum, String priKey) {
        String signKey = "";
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(hexStrToBytes(priKey));
            KeyFactory keyf = KeyFactory.getInstance("RSA");
            PrivateKey myprikey = keyf.generatePrivate(priPKCS8);
            // 用私钥对信息生成数字签名
            java.security.Signature signet = java.security.Signature.getInstance("MD5withRSA");
            signet.initSign(myprikey);
            signet.update(custNum.getBytes("ISO-8859-1"));
            byte[] signed = signet.sign(); // 对信息的数字签名
            signKey = bytesToHexStr(signed);
        } catch (java.lang.Exception e) {
            LOGGER.error("SignatureData.getSignKey", e);
        }
        return signKey;
    }

    /**
     * Transform the specified byte into a Hex String form.
     */
    public static final String bytesToHexStr(byte[] bcd) {
        StringBuilder s = new StringBuilder(bcd.length * 2);

        for (int i = 0; i < bcd.length; i++) {
            s.append(bcdLookup[(bcd[i] >>> 4) & 0x0f]);
            s.append(bcdLookup[bcd[i] & 0x0f]);
        }
        return s.toString();
    }

    /**
     * Transform the specified Hex String into a byte array.
     */
    public static final byte[] hexStrToBytes(String s) {
        byte[] bytes;
        bytes = new byte[s.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2), 16);
        }
        return bytes;
    }

    /**
     * BASE64加密
     * 
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptBASE64(String key) throws Exception {
        return (new BASE64Encoder()).encodeBuffer(key.getBytes("UTF-8")).replace("=", "@").replace("\r", "")
                .replace("\n", "");
    }

}
